package com.vjwealth.android.nos.utils

import android.content.Context
import android.net.wifi.WifiManager
import android.os.Build
import android.provider.Settings
import java.io.IOException
import java.io.InputStreamReader
import java.io.LineNumberReader

/**
 * projectName KNOS
 * date 2017/10/10
 * description com.vjwealth.android.nos.utils
 */
class DeviceUtils {

    companion object {
        /**
         * 获取系统版本号
         */
        fun getSDK(): Int {
            return Build.VERSION.SDK_INT
        }


        /**
         * 获取AndroidID
         *
         * @param context 上下文
         * @return AndroidID
         */
        fun getAndroidID(context: Context): String {
            return Settings.Secure.getString(context.contentResolver, Settings.Secure.ANDROID_ID)
        }

        /**
         * 获取设备MAC地址
         *
         * 需添加权限 `<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>`
         *
         * @param context 上下文
         * @return MAC地址
         */
        fun getMacAddress(context: Context): String? {
            val wifi = context.getSystemService(Context.WIFI_SERVICE) as WifiManager
            val info = wifi.connectionInfo
            if (info != null) {
                val macAddress = info.macAddress
                if (macAddress != null) {
                    return macAddress.replace(":", "")
                }
            }
            return null
        }

        /**
         * 获取设备MAC地址
         *
         * 需添加权限 `<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>`
         *
         * @return MAC地址
         */

        fun getMacAddress(): String {
            var macAddress: String? = null
            var lnr: LineNumberReader? = null
            var isr: InputStreamReader? = null
            try {
                val pp = Runtime.getRuntime().exec("cat /sys/class/net/wlan0/address")
                isr = InputStreamReader(pp.inputStream)
                lnr = LineNumberReader(isr)
                macAddress = lnr.readLine().replace(":", "")
            } catch (e: IOException) {
                e.printStackTrace()
            } finally {
                lnr!!.close()
                isr!!.close()
            }
            return if (macAddress == null) "" else macAddress
        }

        /**
         * 获取设备厂商，如Xiaomi
         *
         * @return 设备厂商
         */
        fun getManufacturer(): String {
            return Build.MANUFACTURER
        }

        /**
         * 获取设备型号，如MI2SC
         *
         * @return 设备型号
         */
        fun getModel(): String {
            var model: String? = Build.MODEL
            if (model != null) {
                model = model.trim { it <= ' ' }.replace("\\s*".toRegex(), "")
            } else {
                model = ""
            }
            return model
        }
    }
}